# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os

import django
import logging
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import Template, Context
from randomizr.models import Decision

def randomizr(request, randURI):
    htmlstr = "RandomizR View called with URI: %s" % randURI
    logging.info(htmlstr)
    icontext = Context()    
    decisions = Decision.all().filter('uri = ', randURI)
    if decisions.count()==0:
        return create(request, "RandomizR with URI: <b>%s</b> doesn't exists, but you can make it now..." % randURI)
    decision = decisions[0]
    icontext['question'] = decision.question;
    icontext['options'] = decision.options[1:];
    icontext['1stOpt'] = decision.options[0]
    decision.popularity += 1
    decision.put()
    logging.info(decision.popularity)
    return render_to_response("randomizr.html", icontext)
  
def create(request, msg=False):
    if request.method == 'POST':
        logging.info("POST CALLED!!!!!!!!!!")
        Question = request.POST["question"]
        optnum = request.POST["optnum"]
        Uri = request.POST["uri"]
        if Decision.all().filter('uri = ', Uri).count()>0:
            icontext = Context()
            icontext['decs'] = Decision.all().order('-popularity')[:5]
            icontext['msg'] = "RandomizR with URI: <b>%s</b> already exists, but you can change that address..." % Uri
            return render_to_response("create.html", icontext)       
        Options = []
        for i in range(1,int(optnum)+1):
            if not request.POST["opt" + str(i)]=='':
                Options.append(request.POST["opt" + str(i)])
        if len(Options)<2:
            icontext = Context()
            icontext['decs'] = Decision.all().order('-popularity')[:5]
            icontext['msg'] = "You need at least two options for THE game..."
            return render_to_response("create.html", icontext)
        tempDec = Decision(question=Question, options = Options, uri=Uri)
        tempDec.put()
        htmlstr = "<html><body>ADD View called, randomizer Added:%s </body></html>" % Uri
        return randomizr(request, Uri)
    elif request.method == 'GET':
        icontext = Context()
        icontext['decs'] = Decision.all().order('-popularity')[:5]
        icontext['msg'] = msg
        return render_to_response("create.html", icontext)
